# -*- coding: utf-8 -*-
from setting import __formnames__
# 需要做的检验批表格名称
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from view import *
from threading import Thread
from queue import Queue
from openpyxl import load_workbook
import numpy as np
from setting import __checkprojects__, ClassName
from multiprocessing import cpu_count


def auto_save_file(path):
    # 文件名重复命名
    directory, file_name = os.path.split(path)
    while os.path.isfile(path):
        pattern = '(\d+)\)\.'
        if re.search(pattern, file_name) is None:
            file_name = file_name.replace('.', '(0).')
        else:
            current_number = int(re.findall(pattern, file_name)[-1])
            new_number = current_number + 1
            file_name = file_name.replace(f'({current_number}).', f'({new_number}).')
        path = os.path.join(directory + os.sep + file_name)
    return path


def timer(func):
    def func_wrapper(*args, **kwargs):
        from time import time
        time_start = time()
        result = func(*args, **kwargs)
        time_end = time()
        time_spend = time_end - time_start
        print('%s cost time: %.3f s' % (func.__name__, time_spend))
        return result

    return func_wrapper


class ProjectInForMation(object):

    def __init__(
            self, excel_path: str = TEMPLATES['端口']['内容输入的界面2'], inport_sheetname=None):

        self.INFO_QUEUE = None
        self.projectInformation = {}
        self.excel_path = excel_path

        self.sheetnames = load_workbook(self.excel_path).sheetnames

        if inport_sheetname in self.sheetnames:

            self.SheetName = inport_sheetname
            self.DIR_DATAFRAME = pd.read_excel(
                self.excel_path, sheet_name='主页', usecols=[0, 1])

            self.DIR_DATAFRAME2 = pd.read_excel(
                self.excel_path, sheet_name='主页', usecols=[
                    5, 6], header=1)

            self.projectInformation = {item[0]: item[1]
                                       for item in self.DIR_DATAFRAME.values}

            self.excel_path = excel_path

            self.DIR_DATAFRAME = self.DIR_DATFARAME1()

            self.cols = self.DIR_DATAFRAME.shape[0]

            self.ProjectInformation1()
        else:
            print(f'{inport_sheetname}不存在')

            return

    def DIR_DATFARAME1(self):

        DIR_DATEFRAME = pd.read_excel(
            self.excel_path,
            sheet_name=self.SheetName,
            header=1)
        DIR_DATEFRAME = DIR_DATEFRAME[DIR_DATEFRAME['是否制作'] == '√']
        return DIR_DATEFRAME

    def ProjectInformation1(self):
        self.INFO_QUEUE = Queue()

        for col in range(self.cols):

            projectInformation = {
                key: value for key, value in zip(__checkprojects__[self.SheetName], self.DIR_DATAFRAME.iloc[col])
            }

            projectInformation = dict(
                self.projectInformation,
                **projectInformation)

            data = np.array([list(projectInformation.keys()),
                             list(projectInformation.values())]).T
            df = pd.DataFrame(data, columns=['check_projcet', 'check_value'])
            df2 = df[df['check_value'].notnull()]
            new_check = set(df2.check_projcet.to_list())
            old_check = set(df.check_projcet.to_list())
            dir_project = old_check.difference(new_check)

            for item in dir_project:
                projectInformation[item] = ''

            self.INFO_QUEUE.put(projectInformation)


class MiddleWare(Thread):

    def __init__(self, inport_sheetname, INFO_QUEUE) -> None:
        super().__init__()

        self.inport_sheetname = inport_sheetname

        self.Project_InForMation_Queue = INFO_QUEUE

        self.run()

    def run(self) -> None:

        while True:

            try:
                ProjectInForMation = self.Project_InForMation_Queue.get(block=False)

            except Exception:

                break
            # try:
            modules = __import__('view')

            # 以下是模板的特殊情况介绍
            # 以下是不同分类模板的相互之间的数据穿插和结果的集合

            if self.inport_sheetname == '砖地面' and ProjectInForMation['地砖类型'] in ['缸砖', '水泥花砖', '陶瓷锦砖',
                                                                                        '陶瓷地砖']:
                class_name = '砖地面1'

            elif self.inport_sheetname == '砖地面' and ProjectInForMation['地砖类型'] in ['大理石面层', '花岗石面层',
                                                                                          '碎拼大理石',
                                                                                          '碎拼花岗石面层']:
                class_name = '砖地面2'

            else:
                class_name = ClassName[self.inport_sheetname]

            getattr(modules, class_name)(project_information=ProjectInForMation, inport_sheetname=self.inport_sheetname)


# 合并表格


class Choose_process():
    @classmethod
    def choose_process1(project_information: dict[str]):


        def Process1(choice):
            ProjectInForQueue = ProjectInForMation(inport_sheetname=choice).INFO_QUEUE
            max_workers = ProjectInForQueue.qsize()

            with ThreadPoolExecutor(max_workers=max_workers + 1) as executor:
                executor.submit(MiddleWare, choice, ProjectInForQueue)
            executor.shutdown()

        """_summary_
        
        @project_information:项目基本信息的导入

        Returns:
            _type_: _description_
        """
        # 检验批的整体选项

        for number, choose in enumerate(__formnames__):
            print(f"序号{number}:{choose}")
        choose = input("请输入需要做的表格名称的序号（如若选择多个请用顿号隔开）：")

        chooses = [__formnames__[int(choose)] for choose in choose.split(",")]

        max_workers = min(cpu_count, len(chooses))

        with ProcessPoolExecutor(max_workers=max_workers) as executor:
            executor.map(Process1, chooses)

        executor.shutdown()

        return main()

    def choose_process2(project_information: dict):
        # 检验批的整体选项

        df = pd.read_excel(io=TEMPLATES['端口']['隐蔽验收输入界面'], sheet_name='Sheet1', header=0)
        newdf = df[df['是否制作'] == '✓']
        print(newdf)


        for x in range(newdf.shape[0]):

            project_information1 = dict(project_information, **pd.Series(newdf.iloc[x]).to_dict())
            

            _new_path_ = os.path.join(TEMPLATES['端口']['输出'],f'{newdf["检验批部位"].iloc[x]}隐蔽验收记录.xlsx')

            _new_path_ = auto_save_file(_new_path_)

            CommonCheck(project_information1, _new_path_)


@timer
def main():
    while True:

        df = pd.read_excel(io=TEMPLATES['端口']['项目基本信息输入界面'], sheet_name='Sheet1', header=0)

        for x in range(df.shape[0]):
            print(f'序号{x}:{df["项目名称"].iloc[x]}')

        project_choose = int(input("请输入需要处理的项目序号："))

        project_information = df.iloc[project_choose].to_dict()

        new_choose = ['检验批', '隐蔽验收记录']

        choose_fuc = ['choose_process1', 'choose_process2']

        for number, choose in enumerate(new_choose):
            print(f"序号{number}:{choose}")

        new_choose_input = int(input("请输入需要处理工序："))
        print(new_choose_input)

        if hasattr(Choose_process, choose_fuc[new_choose_input]):
            getattr(Choose_process, choose_fuc[new_choose_input])(project_information)

        print('选择退出（q）/继续（p），如若继续，请按p;如若退出，请按q')
        choose = input('请选择：')

        if choose.strip() == 'p':
            return main()

        break


if __name__ == "__main__":
    main()

    pass
